import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { toast, base, createPage } from 'nc-lightapp-front';
import { initTemplate, afterEvent, searchClick } from './events';
import requestApi from './requestApi';
import { setSearch } from 'src/erm/sscrppublic/common/utils/setComponentUsed'
import './index.less';
const  { NCButton } = base

window.invoicePageCode = {
    searchPage: '201102BCLF_FPLC'
};
window.InvoiceWalletAreaCode = {
    searchArea: 'search',
    billsArea: 'head',
    bodysArea: 'body'
};

export default class InvoiceWallet extends Component {
    deleteList = {}; //待删除列表
    invoiceList = []; //当前展示的发票列表数据 [{head: {head: {}}, body:{body: {}}}]  body是可选的
    constructor(props) {
        super(props);
        setSearch(props, window.InvoiceWalletAreaCode.searchArea)
        this.state = {
            showInvoiceWalletModal: true,
        }

        let { search } = this.props;
        let { setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据

        this.isError = false; //转单编辑后字段是否通过验证
        // if (this.props.showInvoiceWalletModal) {
        //     initTemplate.call(this, props);
        // }
    }

    componentDidMount() {
        if (this.props.showInvoiceWalletModal) {
            initTemplate.call(this, this.props);
        }
    }

    setTransferBtnDisabled(flag) {
        //设置“冲借款”按钮是否可用
        // let btnObj = document.querySelector('.area-right .main-button');
        let btnObj = document.querySelector('.area-right .wui-button-text-wrap'); // 平台按钮元素更改，获取方式更改 
        if (flag == true) {
            btnObj&&btnObj.setAttribute('disabled', true);
        } else {
            btnObj&&btnObj.removeAttribute('disabled');
        }

    }

    selectArea = () => {
        let { getTradeType } = this.props;
        const multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        const that = this;
        return <NCButton 
            colors="info"
            onClick={
                () => {
                    if(Object.keys(this.deleteList).length > 0) {
                        const list = []
                        for(const key in this.deleteList) {
                            if(this.deleteList[key]) {
                                list.push(key)
                            }
                        }
                        const param = {invoicePkList: list, pk_psndoc: getTradeType('jkbxr').value , pk_org: getTradeType('pk_org').value}
                        console.log('delete list param:', param)
    
                        requestApi.delete({
                            data: param,
                            success: (data) => {
                                if (data.success){
                                    toast({content:'删除成功!',color:'success'});
                                }else{
                                    toast({content:'删除失败!' + data.errormsg, color:'warning'});
                                }
                                
                                // 刷新列表
                                if (this.props.showInvoiceWalletModal) {
                                    initTemplate.call(that, that.props);
                                }
                            }
                        })
                    } else {
                        toast({content:'请选择待删除的数据!', color:'warning'});
                    }

                }
            }
            size="sm"
        >{multiLang && multiLang.get('201103INUP-0001')}</NCButton>
    }

    render() {
        let { search, transferTable, getTradeType } = this.props;
        let { NCCreateSearch } = search;
        let { createTransferTable } = transferTable;
        const multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId

        return (
            <div className="container">

                <div className="content-wrap">
                    
                    {NCCreateSearch(
                        window.InvoiceWalletAreaCode.searchArea,//模块id
                        {
                            clickPlanEve: searchClick.bind(this),//点击高级面板中的查询方案事件
                            clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                            defaultConditionsNum: 1, //默认显示几个查询条件
                            onAfterEvent: afterEvent()//编辑后事件
                        }
                    )}
                </div>
                <div className="area-content">
                    <div className='area-content-center' id="transferInvoiceWallet">
                        {createTransferTable(
                            {
                                headTableId: window.InvoiceWalletAreaCode.billsArea,//表格组件id
                                bodyTableId: window.InvoiceWalletAreaCode.bodysArea,//子表模板id
                                fullTableId: window.InvoiceWalletAreaCode.bodysArea,//主子拉平模板id
                                //点击加号展开，设置表格数据
                                transferBtnText: multiLang && multiLang.get('201103INUP-0005'), //转单按钮显示文字
                                containerSelector: '#transferInvoiceWallet', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                                selectArea: this.selectArea,
                                onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                                    console.log('selected ids:',ids)
                                    const invoicePkList = []
                                    if(ids&&ids.length > 0) {
                                        ids.forEach(item => {
                                            invoicePkList.push(item.head.pk)
                                        })
                                    }
                                    
                                    if(!getTradeType('pk_tradetypeid')) {
                                        toast({content: '交易类型字段不能为空!'}); 
                                        return
                                    }
                                    const tradetype = getTradeType('pk_tradetypeid').value

                                    const pjdata = {
                                        "invoicePkList" : invoicePkList,
                                        "tradetype" : tradetype
                                    }  

                                    const list = this.props.transferTable.getTransferTableSelectedValue().head || []
                                    let err = false
                                    if(list.length > 0) {
                                        for(let i = 0; i < list.length; i++) {
                                            const item = list[i]
                                            if(Number(item.head.head.rows[0].values.purchaserstatus.value) >= 36) {
                                                toast({content: '存在已报销的发票', color: 'danger'})
                                                err = true
                                                break   
                                            }
                                        }
                                    }
                                    if(!err) {
                                        window.pageInvoiceToBxClick(pjdata);
                                    }
                                },
                                onCheckedChange: (flag, record, index, bodys) => {
                                    console.log('select record:',record)
                                    //全选
                                    
                                    if(Array.isArray(record)) {
                                        const keys =  record.map(itm => itm.pk_erminvoice.value)
                                        keys.forEach(key => {
                                            if (flag == true) {
                                                this.deleteList[key] = true
                                            } else if (flag == false) {
                                                this.deleteList[key] = false
                                            }
                                        })
                                    } else {
                                        //单选条件
                                        const key = record.pk_erminvoice.value
                                        let child_key = record.pk_erminvoice_b && record.pk_erminvoice_b.value
                                        //勾选子表 -> 全选
                                        let body_keys = []
                                        this.invoiceList.forEach(item => {
                                            if(item.head.head.rows[0].values.pk_erminvoice.value === key) {
                                                if(item.body) {
                                                    body_keys = item.body.body.rows.map(_itm => {  
                                                        if(_itm.values.pk_erminvoice_b.value !== child_key) return _itm.values.pk_erminvoice_b.value }
                                                    )
                                                }
                                            }
                                        })
                                        //只勾选兄弟元素，否则计算错误
                                        body_keys = body_keys.filter(itm => itm && itm)
                                        
                                        if(child_key && body_keys.length > 0 && flag) {
                                            this.props.transferTable.setTheCheckRows('head', body_keys)
                                        }
                                        if(child_key && body_keys.length > 0 && (!flag)) {
                                            this.props.transferTable.cancelRowsChecked('head', [key])
                                        }

                                        if (flag == true) {
                                            this.deleteList[key] = true
                                        } else if (flag == false) {
                                            this.deleteList[key] = false
                                        }
                                    }

                                },
                                onChangeViewClick: () => {//点击切换视图钩子函数
                                    if (!this.props.meta.getMeta()[window.InvoiceWalletAreaCode.bodysArea]) {
                                        initTemplate.call(this, this.props); //加载主子拉平模板
                                    }
                                    this.props.transferTable.changeViewType(this.headTableId);
                                }
                            })}
                    </div>

                </div>
            </div>

        )
    }
}

InvoiceWallet = createPage({
    mutiLangCode: '2011'
})(InvoiceWallet);

ReactDOM.render(<InvoiceWallet />, document.querySelector('#app'))